<template>
  <div class="employee_hour_count">
    <one-title title="员工工时统计" @refreshData="refresh"></one-title>
    <div class="fixed_top_56">
      <div class="multiple_search">
        <div class="search_item">
          <div class="select_label">
            选择班组：
          </div>
          <div class="search_wrapper">
            <el-select
              v-model="workgroupId"
              placeholder="请选择班组"
              @change="handleGroup"
              size="small">
              <el-option
                v-for="(item,index) in workGroup"
                :key="index"
                :label="item.NAME"
                :value="item.ID">
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="search_item">
          <div class="select_label">
            选择员工：
          </div>
          <div class="search_wrapper">
            <el-select
              v-model="staffIds"
              multiple
              collapse-tags
              placeholder="请选择员工"
              size="small">
              <el-option
                v-for="(item,index) in staffList"
                :key="index"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="search_item">
          <span class="search_label">工序完工日期：</span>
          <el-date-picker
            v-model="completionDate"
            type="daterange"
            size="small"
            align="right"
            :clearable=false
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            :default-time="['00:00:00', '23:59:59']"
            :picker-options="pickerOptions">
          </el-date-picker>
        </div>
        <div class="mes_btn">
          <el-button
            type="primary"
            icon="el-icon-search"
            class="search_btn"
            @click="getDetailData">
          </el-button>
        </div>
      </div>
      <div class="chart_box">
        <div ref="myChart" class="chart_wrapper"></div>
      </div>
      <div class="table_container">
        <el-table
          :data="listData"
          ref="mesTable"
          max-height="440"
          v-loading="isLoading"
          border
          stripe
          @sort-change="_sort"
          tooltip-effect="dark">
          <el-table-column
            label="员工名称"
            width="200">
            <template slot-scope="scope">
              {{scope.row.staffName + '/' + scope.row.staffNumber}}
            </template>
          </el-table-column>
          <el-table-column
            prop="wgroupName"
            label="班组"
            show-overflow-tooltip
            min-width="200"
            align="center">
          </el-table-column>
          <el-table-column
            prop="plannedTime"
            label="计划工时"
            show-overflow-tooltip
            sortable="custom"
            min-width="200"
            align="center">
          </el-table-column>
          <el-table-column
            prop="expendTime"
            label="实际工时"
            show-overflow-tooltip
            sortable="custom"
            min-width="200"
            :resizable="false"
            align="center">
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>

export default {
  name: 'EmployeeHourCount',
  data() {
    return {
      isLoading: false, // 加载
      workgroupId: '', // 班组
      staffIds: [], // 人员
      sortData: {}, // 排序对象
      completionDate: [
        this.moment(window.serverTime).subtract(1, 'months').format('YYYY-MM-DD 00:00:00'),
        this.moment(window.serverTime).format('YYYY-MM-DD 23:59:59')
      ],
      pickerOptions: this.$dateConfig.pickerOptions // 日期格式的快捷键配置项
    }
  },
  computed: {
    // 班组
    workGroup() {
      return this.$store.state.employeeHourCount.workGroup
    },
    // 人员
    staffList() {
      return this.$store.state.employeeHourCount.staffList.list
    },
    // 图表数据
    listData() {
      return this.$store.state.employeeHourCount.listData || []
    },
  },
  mounted() {
    this.init()
  },
  methods: {
    async init() {
      await this.getWorkGroup()
      await this.getStaffList()
      this.getDetailData()
    },
    // 班组
    handleGroup() {
      this.getStaffList()
    },
    // 获取班组列表
    async getWorkGroup() {
      return this.$store.dispatch('saveData', {
        method: 'get',
        url: 'a/workgroup/workgroup/listfields/id,name',
        module: 'employeeHourCount',
        state: 'workGroup'
      }).then(res => {
        // 默认选中第一个班组
        this.workgroupId = res[0].ID
      })
    },
    // 获取员工列表
    async getStaffList() {
      if (!this.workgroupId) {
        return Promise.resolve(true)
      }
      return this.$store.dispatch('saveData', {
        method: 'post',
        url: 'a/staff/staff/list ',
        data: {
          pageNo: 1,
          pageSize: 999,
          query: {
            columns: ['name'],
            workgroupId: this.workgroupId
          }
        },
        module: 'employeeHourCount',
        state: 'staffList'
      }).then(res => {
        this.staffIds = res.list.reduce((pre, cur) => [...pre, cur.id], [])
      })
    },
    // 刷新
    refresh() {
      this.getDetailData()
      this.searchData = {}
      this.sortData = {}
      this.$refs.mesTable.clearSort()
      this.completionDate = [
        this.moment(window.serverTime).subtract(1, 'months').format('YYYY-MM-DD 00:00:00'),
        this.moment(window.serverTime).format('YYYY-MM-DD 23:59:59')
      ]
    },
    // 初始化方法
    getDetailData() {
      this.isLoading = true
      let postData = {
        method: 'post',
        url: 'a/turnoverworkstage/turnoverWorkstage/staffworktimestatistics',
        data: {},
        module: 'employeeHourCount',
        state: 'listData'
      }
      if (this.workgroupId) {
        postData.data.workgroupId = this.workgroupId
      }
      if (this.staffIds.length) {
        postData.data.staffIds = this.staffIds.join(',')
      }
      if (this.completionDate.length > 0) {
        postData.data.beginWorkStageDate = this.completionDate[0]
        postData.data.endWorkStageDate = this.completionDate[1]
      }
      if (Object.keys(this.sortData).length > 0) {
        postData.data.sort = this.sortData
      }
      this.$store.dispatch('saveData', postData).then(res => {
        // 初始化图表数据
        this.echartsData()
        // 设置图表滚动
        let dataZoom = {
          type: 'slider',
          show: false,
          showDetail: false,
          start: 0,
          end: 100,
          bottom: 10,
          height: 16,
          handleStyle: {
            /*手柄的样式*/
            color: '#fff',
            borderWidth: 2,
            borderColor: '#a1b1c1'
          },
        }
        let max = 12
        if (res.length >= max) {
          dataZoom.end = Math.floor(max / res.length * 100)
          dataZoom.show = true
        }
        this.drawLine(dataZoom)
      }).finally(() => {
        this.isLoading = false
      })
    },
    // 图表所需数据
    echartsData() {
      this.staff = [] // x轴
      this.wgroupName = [] // 班组
      this.plannedTime = [] // 计划工时
      this.expendTime = [] // 实际工时
      this.listData.forEach(item => {
        this.staff.push(item.staffName + '/' + item.staffNumber || '')
        this.wgroupName.push(item.wgroupName || 0)
        this.plannedTime.push(item.plannedTime || 0)
        this.expendTime.push(item.expendTime || 0)
      })
      // this.drawLine()
    },
    // 绘制图表
    drawLine(dataZoom) {
      let myChart = this.$echarts.init(this.$refs.myChart)
      myChart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {type: 'shadow'},
          padding: 10,
          textStyle: {fontSize: 12},
          backgroundColor: 'rgba(0, 0, 0, 0.85)',
        },
        // 缩放,滚动
        dataZoom: dataZoom,
        // 画板边距
        grid: {
          left: '60',
          right: '60',
        },
        legend: {
          data: [
            {name: '计划工时'},
            {name: '实际工时'},
          ],
          itemWidth: 24,
          itemHeight: 10,
        },
        xAxis: [
          {
            type: 'category',
            data: this.staff,
            // x轴轴线颜色和宽度
            axisLine: {
              lineStyle: {
                color: '#dcdfe6',
                width: 2
              }
            },
            // x轴字体颜色
            axisLabel: {
              show: true,
              textStyle: {
                color: 'rgba(0, 0, 0, 0.65)'
              }
            },
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '小时',
            // Y轴虚线
            splitLine: {
              lineStyle: {
                color: 'rgba(0, 0, 0, 0.1)',
                width: 1,
                type: 'dashed'
              }
            },
            // y轴轴线
            axisLine: {'show': false},
            //y轴刻度线
            axisTick: {'show': false},
          }
        ],
        // 数据
        series: [
          {
            name: '计划工时',
            type: 'bar',
            data: this.plannedTime,
            barMaxWidth: 160,
            barMinHeight: 10,
            itemStyle: {
              normal: {
                color: '#1890ff',
                opacity: 0.85
              }
            }
          },
          {
            name: '实际工时',
            type: 'bar',
            data: this.expendTime,
            barMaxWidth: 160,
            barMinHeight: 10,
            itemStyle: {
              normal: {
                color: '#37cccc',
                opacity: 0.85
              }
            }
          },
        ]
      })
    },
    // 排序
    _sort(obj) {
      this.sortData = this.$getSortOrder(obj)
      this.getDetailData()
    }
  }
}
</script>

<style scoped lang="less">
  .employee_hour_count {
    .chart_box {
      padding: 0 20px;
      .chart_wrapper {
        width: 100%;
        height: 500px;
        box-sizing: border-box;
        border: 1px solid #dcdfe6;
        margin-bottom: 20px;
        padding-top: 20px;
      }
    }
    .table_container{
      padding-bottom: 40px;
    }
  }
</style>
